package com.zhang.blog.controller;

import com.zhang.blog.utils.QiniuUtils;
import com.zhang.blog.vo.Result;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName: UploadController
 * @Auther: dell
 * @Date: 2021/11/1 20:20
 * @Description:
 */
@RestController
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private QiniuUtils qiniuUtils;

    @Value("${file.upload.editpicturePath}")
    private String filePath;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        //原始文件名称 比如 aa.png
        String originalFilename = file.getOriginalFilename();
        //唯一的文件名称
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //上传文件 上传到哪呢？ 七牛云 云服务器 按量付费 速度快 把图片发放到离用户最近的服务器上
        // 降低 我们自身应用服务器的带宽消耗

        boolean upload = qiniuUtils.upload(file, fileName);
        if (upload){
            return Result.success(QiniuUtils.url +"/"+ fileName);
        }
        return Result.fail(20001,"上传失败");
    }


        @PostMapping("downloadLocal")
        public Result downloadLocal(@RequestParam("image") MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();//获取文件名称
        String suffixName=fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
        fileName= UUID.randomUUID()+suffixName;//重新生成文件名
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            // 判断文件夹是否未空，空则创建
            targetFile.mkdirs();
        }

        File saveFile = new File(targetFile, fileName);
        try {
            file.transferTo(saveFile);
            Thumbnails.of("E:\\cache\\blog\\editPicture\\"+fileName)
                    .scale(1f)
                    .outputQuality(0.5f)
                    .toFile("E:\\cache\\blog\\editPicture\\"+fileName);
            //指定本地存入路径

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(20001,"上传失败");
        }
        return Result.success("http://localhost:8080/"+ fileName);
    }

}
